<?php
/**
 *
 * @author xnny
 * @version 
 */

/**
 * 博客文章相关
 * @author wangtao
 *
 */
class wt_post
{
	/*
	 * 加入新源
	 * $rss：为源
	 */
	static function addRss($rss, $blogInfo)
	{
		$BID = self::getBlogID($rss);
		if($BID)
		{
			return false;
		}
		else
		{
			$db = mysqlDB::con();
			$sql= 'INSERT INTO `feed`.`blog_info` (`BID`, `Blog_Title`, `Blog_Link`, `Blog_Descripton`, 
			`Blog_LastBuildDate`, `countNUM`, `Blog_Feed`, `blogType`, `Blog_State`) VALUES 
			(NULL , \'' . addcslashes($blogInfo['title'], '\'') . '\', \'' . 
			$blogInfo['link'] .'\', \'' . addcslashes($blogInfo['description'], '\'') . '\', 0, \'0\', \'' . 
			$rss . '\', \'1\', \'1\')';
			if (!$db->query($sql))
			{
				echo $rss . '加入失败' . "\n";
			}
			return true;
		}
	}
	/**
	 * 增加新文章
	 * @param string $rss		RSS
	 * @param array $rssPost	从RSS里提取的文章
	 * @return void
	 */
	static function addPostNew($rss, $rssPost)
	{
		$db = mysqlDB::con();
		$BID = self::rss2BID($rss);
		foreach($rssPost as $newPost)
		{
		//	print_r($newPost);
			$postTitle = $newPost['postTitle'];
			$postLink = $newPost['postLink'];
			$pubDate = empty($newPost['pubDate']) ? date('Y-m-d H:i:s') : $newPost['pubDate'];
			$postCreator = $newPost['postCreator'];
			$postContentEncoded = $newPost['postContentEncoded'];
			$pid = self::getNowPid();
			$sql = 'INSERT INTO `feed`.`post_into` (`Pid`, `Post_Title`, `Post_Link`, `Post_PubDate`, `Post_Creator`, 
			`Post_Content`, `BID`) VALUES 
			(\'' . $pid . '\' , \'' . addcslashes($postTitle, '\'') . '\', \'' . $postLink . '\', \'' . 
			$pubDate . '\', \'' . addcslashes($postCreator, '\'') . '\', \'' . 
			addcslashes($postContentEncoded, '\'') . '\', \'' . $BID . '\');';
			#$sql2 = 'UPDATE `feed`.`blog_info` SET `Blog_LastBuildDate` = \'' . $newPost['pubDate'] . '\', `countNUM` = `countNUM` +1 WHERE `blog_info`.`Blog_Feed` = \'' . $rss . '\';';
			if ($db->query($sql))
			{
				self::addBidPidNum($BID, $pid);
				echo '.';
			}
			else
			{
				echo '更新失败' . $newPost['feed'] . "\n";
				exit();
			}
			#$db->query($sql2);
		}
		echo "\n" . '<br>么么哒，更新成功！';
	}
	
	/**
	 * 扩展strtotime函数
	 * @param string $string
	 */
	public static function strtotimeExtend($string)
	{
		preg_match('/[\x81-\xfe][\x40-\xfe]/', $string, $time);
		if (empty($time[0]))
		{
			$date = strtotime($string);
		}
		else
		{
			$string = str_replace('(', '', $string);
			$string = str_replace(')', '', $string);
			$string = str_replace('年', '-', $string);
			$string = str_replace('月', '-', $string);
			$string = str_replace('日', '', $string);
			$string = iconv('gb2312', 'utf-8//IGNORE', $string);
			$string = preg_replace('/[\x81-\xfe][\x40-\xfe]/', '', $string);
			$date = strtotime($string);
		}
		return $date;
	}
	
	public static function isValidUtf8($str)
	{
		$out = iconv('utf-8','utf-8',$str);
		return $out == $str ? 1 : 0;
	}
	
	/**
	 * 根据RSS返回BID
	 * @param string $rss	RSS
	 * @return string
	 */
	static function rss2BID($rss)
	{
		$db = mysqlDB::con();
		$sql = 'SELECT `BID` FROM `blog_info` WHERE `Blog_Feed` = \'' . $rss . '\'';
		$BID = $db->query2one($sql);
		return $BID;
	}
	
	/*
	 * 提取已经定阅的源
	 * 返回源地址的数组
	 */
	static function getRss()
	{
		$db = mysqlDB::con();
		$sql = 'SELECT `Blog_Feed` FROM `blog_info`';
		$feed = $db->selectLimit($sql);
		foreach($feed as $value)
		{
			$rss[] = $value['Blog_Feed'];			
		}
		return $rss;
	}
	
	/*
	 * 查询文章地址，不存在文章地址返回false
	 */
	static function selectLink($link)
	{
		$db = mysqlDB::con();
		$linkSql = 'SELECT Pid FROM post_into WHERE `Post_Link` = \'' . $link . '\' LIMIT 1';
		return $db->query2one($linkSql);
	}

	/*
	 * 获得未读文章
	 * 存在未读文章返回文章，不存在返回false
	 * $post：为文章源
	 */
	static function getUnreadArticles($postAll)
	{
		foreach ($postAll as $post)
		{
			$postId = self::selectLink($post['link']);
			if(empty($postId))
			{
				$new_post[] = $post;
			}
			else
			{
				break;
			}
		}
		
		if(empty($new_post))
		{
			return false;
		}
		else
		{
			return $new_post;
		}
	}
	
	/*
	 * 获得指定源最后更新时间
	 * 返回文章最后更新时间
	 * $rss：文章源
	 */
	static function updateRssDate($post)
	{
		$db = mysqlDB::con();
		$sql = 'SELECT `Post_PubDate` FROM post_into WHERE `Post_Feed` = \'' . $post['feed_rss'] . '\' ORDER BY Pid DESC LIMIT 1';//获得最后发表博文的时间。
		if(($date = $db->getOneArr($sql)) || $date)
		{
			return $date['Post_PubDate'];
		}
		else
		{
			//echo '该源没有收入文章';
			return false;
		}
	}
	
	/**
	 * 清理缓存
	 * @access public
	 * @param int $BID	博客ID
	 * @return void
	 */
	static function clearCache($BID)
	{
		$cid = $BID . '-index';
		$views = new smasrty();

		$views->caching = 1;
		$views->clear_cache('main.html', $cid);
	}
	
	/**
	 * 创建缓存
	 * @access public
	 * @param int $BID	博客ID
	 * @return void
	 */
	static function creatCache($BID)
	{
		$db = mysqlDB::con();
		$sql = 'SELECT * FROM `post_into` WHERE `BID` =' . $BID . ' ';
		$sqlS = 'SELECT `Blog_Title`, `countNUM` FROM `blog_info` WHERE `BID` = \'' . $BID . ' \' LIMIT 1';
		$array = $db->getRow($sqlS);
		//获取总数据量
		$conutNum = empty($array['countNUM']) ? 0 : $array['countNUM'];
		$title = empty($array['Blog_Title']) ? 0 : $array['Blog_Title'];
		#生成URL
		$url = '/readRSS/' . $BID;
		if ($conutNum % 10)
		{
			$start = wt_math::gTO0($conutNum);
		}
		elseif ($conutNum % 10 === 0)
		{
			$start = $conutNum - 10;
		}
		$page = http::rssPageF($conutNum, $start, $url);
		$post = array_reverse($db->selectLimit($sql, 10, $start));
		$cid = $BID . '-index';
		$views = new smasrty();

		$views->caching = 1;
		$views->cache_lifetime = -1;
		$views->assign('pager', $page);
		$views->assign('post', $post);
		$views->assign('countNUM', $conutNum);
		$views->assign('title', $title);
		$output = $views->fetch('main.html', $cid);
	}
	
	/**
	 * 清除每段开头的空格
	 * @param string $string	文字
	 * @return string
	 */
	static function clearSpace($string)
	{
		return preg_replace('/<p>[　 ]{2,4}|<p>[　 ]{4,6}|<p>[　 ]{6,8}/', '<p>', $string);
	}
	
	/**
	 * 得到源的ID
	 * @param string $feed  源
	 */
	static function getBlogID($feed)
	{
		#set_time_limit(0);
		$db = mysqlDB::con();
		$sql = 'SELECT `BID` FROM `blog_info` WHERE `Blog_Feed` = \'' . $feed . '\' LIMIT 0 , 1';
		return $db->query2one($sql);
	}
	
	/**
	 * 加入博文
	 * @access public
	 * @param array $p		文章
	 * @param int	$BID	博文ID
	 * @return void
	 */
	static function addPost($p, $BID)
	{
		set_time_limit(0);
		#开始存入数据
		#var_dump($p['postPubDate']);exit;
		$db = mysqlDB::con();
		$dateTime = date('Y-m-d H:i:s');
		$postTitle = $p['postTitle'];
		$postLink = $p['postLink'];
		$postPubDate = empty($p['postPubDate']) ? $dateTime : date('Y-m-d H:i:s', $p['postPubDate']);
		$postCreator = $p['postCreator'];
		$postContentEncoded = $p['postContentEncoded'];
		$pid = self::getNowPid();
		$sql = 'INSERT INTO `feed`.`post_into` (`Pid` ,`Post_Title` ,`Post_Link` ,`Post_PubDate` ,`Post_Creator` ,
		`Post_Content` ,`BID`) VALUES (\'' . $pid . '\' ,\'' . addcslashes($postTitle, '\'') . '\',\'' . $postLink . 
		'\',\'' . $postPubDate . '\',\'' . addcslashes($postCreator, '\'') . '\',\'' . 
		addcslashes($postContentEncoded, '\'') . 
		'\',\'' . $BID . '\')';
		if ($db->query($sql))
		{
			self::insertLink($pid, $postLink);
			self::addBidPidNum($BID, $pid);
		}
		else
		{
			Log::writeLog($BID . "\n", 'er');
		}
		$strPosr = $postTitle . ' => is OK. | link => ' . $postLink . ' | Time:' . $dateTime . "\n";
		Log::writeLog($strPosr);
		//echo '更新成功';
	}
	
	/**
	 * 添加
	 * @param int $bid
	 * @param int $pid
	 */
	static function addBidPidNum($bid, $pid)
	{
		$db = mysqlDB::con();
		$query1 = 'SELECT `num` FROM `bid_pid_num` WHERE `bid` = ' . $bid . ' ORDER BY `num` DESC LIMIT 0 , 1';
		$num = $db->query2one($query1);
		$num += 1;
		$query3 = 'INSERT INTO `bid_pid_num` (`bid`, `pid`, `num`) VALUES (' .  $bid . ', ' . $pid . ', ' . $num . ')';
		$db->query($query3);
	}
	
	static function insertLink($pid, $link)
	{
		$link = md5($link);
		$sql = 'INSERT INTO `feed`.`postLink` (`Pid`, `link`) VALUES 
		(\'' . $pid . '\', \'' . $link . '\');';
		$db = mysqlDB::con();
		$db->query($sql);
	}
	
	/**
	 * 根据链接得到博文ID
	 * @param string $postLink
	 */
	static function postLink2pid($postLink)
	{
		$db = mysqlDB::con();
		$sql = 'SELECT `Pid` FROM `post_into` WHERE `Post_Link` = \'' . $postLink . '\' 
		LIMIT 0 , 1';
		$pid = $db->query2one($sql);
		return $pid;
	}
	
	/**
	 * 得到本条博文的ID，默认为上条博文ID的自加
	 */
	static function getNowPid()
	{
		$db = mysqlDB::con();
		$sql = 'SELECT (`Pid` +1) AS `pid2` FROM `post_into` WHERE 1 ORDER BY `Pid` DESC LIMIT 0 , 1';
		$pid = $db->query2one($sql);
		return $pid;
	}
	
	/**
	 * 得到源最后更新时间
	 * @param string $feed
	 */
	static function getLastUpdate($feed)
	{
		$db = mysqlDB::con();
		$sql = 'SELECT `Blog_LastBuildDate` FROM `blog_info` WHERE 
		`Blog_Feed` = \'' . $feed . '\' LIMIT 0 , 1';
		$lastUpdate = $db->query2one($sql);
		$lastUpdate = empty($lastUpdate) ? '55' : strtotime($lastUpdate);
		return $lastUpdate;
	}
}